package com.fafa.swing.base;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;

/**
 * @author : fafa
 * @version V1.0
 * @Project: SwingTest
 * @Package com.fafa.swing
 * @Description: JListListenerDemo
 * @date Date : 2019年11月24日 20:18
 */
public class JListListenerDemo extends JFrame {

    JList list;
    JLabel label;

    public JListListenerDemo(){
        setTitle("监听列表项选择事件");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(300,300,400,200);
        JPanel contentPane = new JPanel();
        contentPane.setLayout(new BorderLayout(0,0));
        contentPane.setBorder(new EmptyBorder(5,5,5,5));
        setContentPane(contentPane);
        label = new JLabel("        ");
        contentPane.add(label, BorderLayout.SOUTH);
        JScrollPane scrollPane = new JScrollPane();
        contentPane.add(scrollPane,BorderLayout.CENTER);

        list = new JList();
        scrollPane.setViewportView(list);
        String[] listData = new String[7];
        listData[0] = "《一点就通学Java》";
        listData[1] = "《一点就通学PHP》";
        listData[2] = "《一点就通学C++》";
        listData[3] = "《一点就通学Python》";
        listData[4] = "《一点就通学Visual Basic》";
        listData[5] = "《Java编程词典》";
        listData[6] = "《C++编程词典》";
        list.setListData(listData);

        list.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                do_list_valueChange(e);
            }
        });

    }

    protected void do_list_valueChange(ListSelectionEvent e){
        label.setText("感谢您购买："+list.getSelectedValue());
    }

    public static void main(String[] args) {
        JListListenerDemo demo = new JListListenerDemo();
        demo.setVisible(true);
    }
}
